package com.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.pay.util.*;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 微信授权登录
 */
@Controller
public class WxAuthorizedLoginController {

    @Value("${h5appid}")
    private String appid;

    @Value("${appsecret}")
    private String appsecret;

    @Value("${callback}")
    private String callback;

    @Value("${messageId}")
    private String messageId;



    @GetMapping("index")
    public String index(){
        return "index";
    }


    /**
     * 微信授权登录，获取code值
     * @return
     */
    @GetMapping("wxlogin")
    public String wxlogin(){
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid="+appid+
                "&redirect_uri="+callback +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        return "redirect:"+url;
    }


    /**
     * 微信回调返回openid
     * @return
     */
    @GetMapping("wxcallback")
    public String wxcallback(String code, Model model) throws Exception {
        //通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid="+appid+
                "&secret="+appsecret+
                "&code="+code+
                "&grant_type=authorization_code";
        JSONObject jsonObject = H5HttpClientUtils.doGet(url);
        String openid = jsonObject.getString("openid");
        String accessToken = jsonObject.getString("access_token");
        System.out.println(openid);
        System.out.println(accessToken);
        //通过openid与access_Token拉取用户信息
        String url1 = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token="+accessToken+
                "&openid=" +openid+
                "&lang=zh_CN";
        JSONObject userjson = H5HttpClientUtils.doGet(url1);
        model.addAttribute("nickname",userjson.get("nickname"));
        model.addAttribute("headimgurl",userjson.get("headimgurl"));
        System.out.println(userjson.get("headimgurl"));
        return "/home";
    }


    /**
     * 推送公众号模板消息
     */
    @ResponseBody
    @GetMapping("push")
    public void push(){
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(appid);
        wxStorage.setSecret(appsecret);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("osLHC6gPRjZ8JMAOf6apJdBaRYgc")
                .templateId(messageId)
                .build();
        templateMessage.addData(new WxMpTemplateData("DATE","100元"));
        templateMessage.addData(new WxMpTemplateData("TYPE","23点"));
        templateMessage.addData(new WxMpTemplateData("LOW","10积分"));
        try {
            // 发送模板消息
            String id = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
